package l.l.w.leetcode.ReverseNodesInK_Group;

import l.l.w.leetcode.SwapNodesInPairs.SwapNodesInPairs;

/**
 * Created by llw on 2017/11/3.
 */
public class ReverseNodesInK_Group {

    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null) return head;
        boolean isFirst = true;
        ListNode cur = head,start = head, result = head,pre = null,next;
        int i =1;
        while(cur != null){
            next = cur.next;
            if(i % k ==0){
                reverse(start,cur);
                if(isFirst){
                    result = cur;
                    isFirst = false;
                }else{
                    pre.next = cur;

                }
                pre = start;
                pre.next = next;
                start = next;
                cur = next;
                i=1;
            }else{
                i++;
                cur = next;
            }
        }
        return result;
    }

    private void reverse(ListNode start, ListNode end) {
        if(start == end) return;
        ListNode cur = start,pre = null, next=start.next;
        cur.next = pre;
        pre = cur;
        cur = next;
        while(cur != end && cur!=null){
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        end.next = pre;
    }

    public static void main(String[] args) {
        ListNode head = new ListNode(1);
        ListNode n2 = new ListNode(2);
        ListNode n3 = new ListNode(3);
        ListNode n4 = new ListNode(4);
        ListNode n5 = new ListNode(5);
        ListNode n6 = new ListNode(6);
        ListNode n7 = new ListNode(7);
        n6.next = n7;
        n5.next = n6;
        n4.next = n5;
        n3.next = n4;
        n2.next = n3;
        head.next = n2;
        ListNode result = new ReverseNodesInK_Group().reverseKGroup(head,1);
        System.out.println(result);
    }
}
class ListNode {
    int val;
    ListNode next;
    ListNode(int x) { val = x; }
}